<template>
  <div class="Myaddress">
    <van-nav-bar title="地址管理" left-text="返回" left-arrow @click-left="onClickLeft" />
    <BgBox>
      <div>
        <div class="isHas" v-if="list.length>0">
          <van-address-list :list="list" default-tag-text="默认" @add="onAdd" @edit="onEdit" :switchable="false" />
        </div>
        <div v-else>
          <van-empty description="地址为空" />
          <van-button type="primary" size="large" @click="onAdd">新增地址</van-button>
        </div>
      </div>
    </BgBox>
  </div>

</template>

<script>
import request from '@/utils/reques'
import BgBox from '@/components/bgbox.vue'
export default {
  name: 'Myaddress',
  created() {
    this.getAddressData()
  },
  components: {
    BgBox
  },
  data() {
    return {
      list: []
    }
  },
  methods: {
    onAdd() {
      this.$router.push({ name: 'NewAddress' })
    },
    onEdit(item) {
      this.$router.push({ name: 'NewAddress', query: { aid: item.aid } })
    },
    async getAddressData() {
      try {
        let tokenString = localStorage.getItem('token')

        if (!tokenString) {
          this.$toast('请先登录~')
          return this.$router.push({ name: 'Login' })
        }

        this.$toast.loading({
          message: '获取信息中',
          forbidClick: true,
          duration: 0
        })
        const { data: res } = await request.get('/findAddress', {
          params: {
            appkey: this.appkey,
            tokenString
          }
        })

        if (res.code == 700) {
          this.$router.push({ name: 'Login' })
        } else if (res.code == 20000) {
          res.result.map((v) => {
            v.isDefault = Boolean(v.isDefault)
            v.id = v.aid
            v.address = `${v.province}${v.city}${v.county}${v.addressDetail}`
          })
          this.list = res.result
        }
        this.$toast.clear()
      } catch (error) {
        this.$toast.clear()
      }
    },
    onClickLeft() {
      this.$router.go(-1)
    }
  }
}
</script>

<style lang="less" scoped>
.van-button--primary {
  height: 42px;
  border-radius: 20px;
  background-color: #1a73e8;
  border: #1a73e8;
}
.van-button--danger {
  height: 42px;
  border-radius: 20px;
  background-color: #1a73e8;
  border: #1a73e8;
}
.van-address-list__bottom {
  background-color: rgba(0, 0, 0, 0);
}
.van-tag--danger {
  background-color: #1a73e8;
}
</style>